<template>
  <el-dialog title="选择分类" center :visible="dialogVisible" width="30%" @open="load" @close="visible=false">
      <el-tree
        :render-after-expand="false"
        :data="categories"
        show-checkbox
        @check-change="handleCheckChange"
        :key="key"
        >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span class="title">{{ data.name }}</span>
        </span>
      </el-tree>
      <div slot="footer" class="dialog-footer" align="right">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
  </el-dialog>
</template>

<script>
import api from '@/api'
import __ from 'lodash'
export default {
  mounted () {
    this.$bus.$on('toggle-category-dialog', (visible) => {
      this.dialogVisible = true
    })
  },
  data () {
    return {
      key: 100,
      tempCategory: [],
      dialogVisible: false,
      categories: [{
        name: '所有分类',
        id: 0,
        isRoot: true,
        children: []
      }]
    }
  },
  methods: {
    handleCheckChange (data, checked, indeterminate) {
      console.log(JSON.stringify(this.tempCategory))
      if (data.isRoot) {
        return
      }
      if (checked) {
        this.tempCategory.push(data.id)
      } else {
        __.remove(this.tempCategory, function (item) {
          return item === data.id
        })
      }
      console.log(JSON.stringify(this.tempCategory))
    },
    confirm () {
      this.dialogVisible = false
      this.$emit('on-category-confirm', this.tempCategory)
      this.key++
      this.tempCategory = []
    },
    load () {
      api.getAllCategories().then(api.commonResp((success, data) => {
        if (success) {
          console.log(JSON.stringify(data))
          this.categories[0].children = data
          console.log(JSON.stringify(this.categories))
        } else {
          this.$message.error(data)
        }
      }))
    }
  }
}
</script>

<style scoped lang="less">
  .custom-tree-node {
    .title {
      margin-right: 20px;
    }
  }
</style>
